package com.vcredit.creditcat.framework.util;

import java.math.BigDecimal;
import java.text.DecimalFormat;
/**
 * Double数字工具
 *
 */
public class NumberUtil {
	private static DecimalFormat format = new DecimalFormat(".00");
	
	public static String toString(Double d, String format) {
		return new DecimalFormat(format).format(d);
	}

	public static double sum(double d1, double d2) {
		BigDecimal bd1 = new BigDecimal(Double.toString(d1));
		BigDecimal bd2 = new BigDecimal(Double.toString(d2));
		return bd1.add(bd2).doubleValue();
	}

	public static double sub(double d1, double d2) {
		BigDecimal bd1 = new BigDecimal(Double.toString(d1));
		BigDecimal bd2 = new BigDecimal(Double.toString(d2));
		return bd1.subtract(bd2).doubleValue();
	}

	public static double times(double d1, double d2) {
		BigDecimal bd1 = new BigDecimal(Double.toString(d1));
		BigDecimal bd2 = new BigDecimal(Double.toString(d2));
		return bd1.multiply(bd2).doubleValue();
	}

	public static double divide(double d1, double d2, int scale) {
		BigDecimal bd1 = new BigDecimal(Double.toString(d1));
		BigDecimal bd2 = new BigDecimal(Double.toString(d2));
		return bd1.divide(bd2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
	}

	public static double divide(double d1, double d2) {
		BigDecimal bd1 = new BigDecimal(Double.toString(d1));
		BigDecimal bd2 = new BigDecimal(Double.toString(d2));
		return bd1.divide(bd2).doubleValue();
	}
	
	public static double round(double value, int scale) {
		BigDecimal bd = new BigDecimal(value);
		bd = bd.setScale(scale, BigDecimal.ROUND_HALF_UP);
		double d = bd.doubleValue();
		bd = null;
		return d;
	}
	
	public static Long setLongPrice(String price) {
		BigDecimal bd1 = null;
		try{
			bd1 = new BigDecimal(price);
		}catch(Exception e){
			return 0L;
		}
		return bd1.multiply(new BigDecimal(100)).longValue();
	}
	
	public static String getLongPrice(Long price) {
		BigDecimal bd1 = null;
		try{
			bd1 = new BigDecimal(price);
		}catch(Exception e){
			return "0.00";
		}
		String retPrice = format.format(bd1.divide(new BigDecimal(100)).doubleValue());
		return retPrice.startsWith(".") ? "0"+retPrice : retPrice;
	}
	
}
